<template>
  <base-layout
    :dialog-title="dialogTitle"
    :dialog-visible="dialogVisible"
    @dialog-close="dialogClose"
    :dialogWidth="dialogWidth"
    :visibleContent2="true">
    <template #searchPanel>
      <el-form
        :inline="true"
        ref="fromdata"
        :show-message="true"
        :model="fromdata"
        :rules="rules"
        label-width="100px"
        label-position="right"
      >
        <el-row class="">
          <el-col :span="12">配件信息</el-col>
        </el-row>
        <el-divider content-position="center"></el-divider>
        <el-row>
          <el-form-item label="配件编号:">
            <el-input clearable v-model="fromdata.partsCode"/>
          </el-form-item>
          <el-form-item label="配件名称:" prop="partsName">
            <el-input clearable v-model="fromdata.partsName" placeholder="请输入"/>
          </el-form-item>
          <el-form-item label="所属门店:" prop="storeId">
            <job-shop v-model="fromdata.storeId" placeholder="所属门店" />
          </el-form-item>
          <el-form-item label="配件类别:" prop="partsDictId">
            <el-select
              clearable
              ref="dragSelect"
              v-model="fromdata.partsDictId"
              class="drag-select"
            >
              <el-option
                v-for="item in dict.typeOptions['汽车配件类型']"
                :key="item.index"
                :value="item.value"
                :label="item.text"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="配件供应商:" prop="supplierId">
            <el-select
              clearable
              ref="dragSelect"
              v-model="fromdata.supplierId"
              class="drag-select"
            >
              <el-option
                v-for="item in dict.supplierOptions"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="配件单位:" prop="unit">
            <el-input clearable v-model="fromdata.unit" placeholder="如：个，组，桶，件"/>
          </el-form-item>
          <el-form-item label="配件型号:" prop="partsModel">
            <el-input clearable v-model="fromdata.partsModel" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="一般维修:" prop="ordinaryMaintain">
            <el-radio-group v-model="fromdata.ordinaryMaintain" style="width: 200px">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="内置计数:" prop="internalNum">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="1" step-strictly v-model="fromdata.internalNum" placeholder="内置计数"></el-input-number>
          </el-form-item>
          <el-form-item label="配件来源:" prop="source">
            <el-select
              clearable
              ref="dragSelect"
              v-model="fromdata.source"
              class="drag-select"
            >
              <el-option
                v-for="item in dict.typeOptions['配件来源']"
                :key="item.index"
                :value="item.value"
                :label="item.text"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="含税配件:" prop="taxParts">
            <el-radio-group v-model="fromdata.taxParts" style="width: 200px">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="采购单价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.purchasePrice" placeholder="采购单价"></el-input-number>
          </el-form-item>
          <el-form-item label="税率:">
            <el-input-number clearable
              v-if="fromdata.taxParts" 
              :controls="false" :min="0" 
              :max="999999999" 
              :step="0.01" 
              step-strictly 
              v-model="fromdata.taxRate" 
              placeholder="税率"></el-input-number>
          </el-form-item>
          <el-form-item label="含税采购价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.taxPurchasePrice" placeholder="含税采购单价"></el-input-number>
          </el-form-item>
          <el-form-item label="销售价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.salePrice" placeholder="销售价"></el-input-number>
          </el-form-item>
          <el-form-item label="内部价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.enterprisePrice" placeholder="结算价"></el-input-number>
          </el-form-item>
          <el-form-item label="调拨价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.allocationPrice" placeholder="结算价"></el-input-number>
          </el-form-item>
          <el-form-item label="批发价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.tradePrice" placeholder="结算价"></el-input-number>
          </el-form-item>
          <el-form-item label="索赔价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.claimPrice" placeholder="结算价"></el-input-number>
          </el-form-item>
          <el-form-item label="网点价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.outletPrice" placeholder="结算价"></el-input-number>
          </el-form-item>
          <el-form-item label="保险价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.insurancePrice" placeholder="结算价"></el-input-number>
          </el-form-item>
          <el-form-item label="结算价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.settlementPrice" placeholder="结算价"></el-input-number>
          </el-form-item>
          <el-form-item label="成本价:">
            <el-input-number clearable :controls="false" :min="0" :max="999999999" :step="0.01" step-strictly v-model="fromdata.costPrice" placeholder="成本价"></el-input-number>
          </el-form-item>
          
        </el-row>
      </el-form>
    </template>
    <template #contentPanel>
      <el-row>
        <el-col :span="12">配件使用车型</el-col>
        <el-col :span="12" align="right">
          <CarModel v-model="carModels" ref="carModel" />
          <!-- <el-button type="primary"  @click="handleDataInsert('添加车型')">添加车型</el-button> -->
        </el-col>
      </el-row>
      <el-divider content-position="center"></el-divider>
      <el-row>
        <data-table
          :value="tableData"
          :total-count="totalCount"
          :has-action="true"
          :table-column-attributes="tableColumnAttributes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :width="160"
          :isShowPage="false"
        >
          <template #action="{ row }">
            <i
              class="el-icon-delete"
              title="删除"
              style="color:red;cursor: pointer"

              @click="handleDelete(row)"
            ></i>
          </template>
        </data-table>
      </el-row>
    </template>
    <template #contentPanel2>
      <el-row> 配件使用说明 </el-row>
      <el-divider content-position="center"></el-divider>
      <tinymce v-model="fromdata.remark" :height="300"/>
      <el-row>
        <el-col :span="24" align="right">
          <el-button type="primary" @click="onSubmit">保存</el-button>
        </el-col>
      </el-row>
    </template>
    <template #dialog>
      <dialog-data-form @operate="addCarInfo"/>
    </template>
  </base-layout>
</template>
<script>
import { details, addData, updateData } from  '@/api/after-sale/systemManage/accessories'
import {
  getAllBrand,
  getSeries,
  getModelTimeType,
  getModelRank,
  details as modelDetail
} from '@/api/after-sale/systemManage/carModel'
import { dataList } from '@/api/after-sale/systemManage/supplier'
import DialogDataForm from './components/DialogDataForm.vue'
import baseMixin from '@/mixins/base'
import Tinymce from '@/components/Tinymce'
import { getDict } from '@/utils/index'
export default {
  components: { Tinymce, DialogDataForm },
  mixins: [baseMixin({})],
  data() {
    return {
      dialogWidth: '1200px',
      carModels: [],
      carModelData: {},
      fromdata: {
        carModelIds: [],
        internalNum: 1,
        partsCode: '',
        partsDictId: '',
        partsModel: '',
        ordinaryMaintain: '',
        source: '',
        partsName: '',
        purchasePrice: '',
        remark: '',
        status: true,
        storagePrice: '',
        storeId: '',
        supplierId: '',
        taxParts: true,
        taxRate: 13
      },
      rules: {
        partsName: [{ required: true, message: '配件名称不能为空', trigger: 'blur' }],
        supplierId: [{ required: true, message: '配件供应商不能为空', trigger: 'blur' }],
        partsDictId: [{ required: true, message: '配件类别不能为空', trigger: 'blur' }],
        type: [{ required: true, message: '所属类别不能为空', trigger: 'blur' }],
        partsCode: [{ required: true, message: '配件编号不能为空', trigger: 'blur' }],
        unit: [{ required: true, message: '配件单位不能为空', trigger: 'blur' }],
        partsModel: [{ required: true, message: '配件型号不能为空', trigger: 'blur' }],
        source: [{ required: true, message: '配件来源不能为空', trigger: 'change' }],
        internalNum: [{ required: true, message: '内置计数不能为空', trigger: 'blur' }]
      },
      dialogImageUrl: '',
      tableData: [],
      tableColumnAttributes: [
        { name: '品牌', value: 'carBrandName', type: 'text' },
        { name: '车系', value: 'carSeriesName', type: 'text' },
        { name: '年款', value: 'timeType', type: 'text' },
        { name: '车型', value: 'carModelName', type: 'text' },
        { name: '备注', value: 'remark', type: 'text' }
      ],
      imageDialogVisible: false,
      dict: {
        supplierOptions: [],
        typeOptions: []
      }
    }
  },
  watch: {
    carModels: {
      deep: true,
      handler (newValue, oldValue) {
        if (newValue.length<1){
          return;
        }
        this.getModelDetail(newValue);
      },
    },
  },
  async created() {
    this.dict.typeOptions = getDict(['汽车配件类型', '是否', '配件来源']);
    const { data } = await dataList({}, 1000, 1);
    if (data.content) {
      this.dict.supplierOptions = data.content.map(e => {
        return {label: e.supplierName, value: e.id}
      })
    }
    const id = this.$route.query && this.$route.query.id;
    if (id){
      const { data } = await details(id);
      if (data){
        this.fromdata = data;
        this.tableData = []
        this.fromdata.carModelIds = []
        data.carModels.forEach(item => {
          this.fromdata.carModelIds.push(item.id)
          let tableColumn = {
            id: item.id,
            carBrandName: item.brandName,
            carSeriesName: item.seriesName,
            timeType: item.timeType,
            carModelName: item.modelName
          }
          this.tableData.push(tableColumn)
        })
      }
    }
  },
  methods: {
    onSubmit() {
      this.$refs.fromdata.validate(valid => {
        if (valid) {
          this.saveData()
        } else {
          return false
        }
      })
    },
    async saveData(){
      const { success } = this.fromdata.id
        ? await updateData(this.fromdata)
        : await addData(this.fromdata)
      if (success) {
        this.$message({
          message: '操作成功',
          type: 'success',
        })
        this.closeRouter();
      } else {
        this.$message.error('操作失败')
      }
    },
    addCarInfo(val) {
      this.tableData.push(val);
      this.fromdata.carModelIds.push(val.carModelId);
      this.dialogVisible = false;
    },
    async getModelDetail(val){
      let carModel = {};
      await getAllBrand().then((res) => {
        res.data.forEach((e)=> {
          if (e.id == val[0]){
            carModel.carBrandName = e.name;
            carModel.carBrandId = e.id;
          }
        })
      })
      await getSeries(val[0]).then((res) => {
        res.data.forEach((e)=> {
          if (e.id == val[1]){
            carModel.carSeriesName = e.name;
            carModel.carSeriesId = e.id;
          }
        })
      })
      await getModelRank(val[0], val[1], val[2]).then((res) => {
        res.data.forEach((e)=> {
          if (e.id == val[3]){
            carModel.carModelName = e.modelName;
            carModel.carModelId = e.id;
          }
        })
      })
      await getModelTimeType(val[0], val[1]).then((res) => {
        res.data.forEach((e)=> {
          // if (e.id == val[2]){
          //   carModel.timeType = e;
          //   carModel.timeTypeId = e;
          // }
          // yewei 2021/4/1
          if (carModel.carModelName.indexOf(e) != -1) {
            carModel.timeType = e;
          }
        })
      })
      this.addCarInfo(carModel);
    },
    handleDelete(row) {
      this.tableData = this.tableData.filter( e => e != row);
      this.fromdata.carModelIds = this.tableData.carModelIds.filter( e => e != row.carModelId);
    }
  }
}
</script>
